package com.cfk.shopmail.product.exception;

/*
    @CreateTime 2021/11/28 16:06
    @CreateBy cfk
*/

import com.cfk.common.exception.BizCodeEnum;
import com.cfk.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 集中处理异常
 */
@Slf4j
// @ResponseBody
// @ControllerAdvice(basePackages = "com.cfk.shopmail.product.controller")

@RestControllerAdvice(basePackages = "com.cfk.shopmail.product.controller")
public class ShopmailExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据检验出现问题{}，异常类型{}", e.getMessage(), e.getClass());

        HashMap<String, String> errorMap = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach( (item) -> {
            String field = item.getField();
            String message = item.getDefaultMessage();
            errorMap.put(field, message);
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", errorMap);
    }


    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("错误：",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
